package com.grupoconstruobras.sigo.configuracion.parametrizacion;

import com.grupoconstruobras.sigo.exhumaciones.caso.datamodel.listener.QueryAbstract;
import com.grupoconstruobras.sigo.exhumaciones.ui.datamodel.IQueryBuilder;

import java.util.Iterator;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.persistence.Query;

import org.richfaces.component.SortOrder;
import org.richfaces.model.SortField;

public class ParamConfigAppQuery extends QueryAbstract<ConsultaParamConfig> implements IQueryBuilder{
	
	public ParamConfigAppQuery() {		
	}

	@Override
	public Query count() {
		StringBuilder query = new StringBuilder("");
		query.append("SELECT COUNT(idparametro) FROM exhumaciones.paramconfigsistema ");
		Query q = entityManager.createNativeQuery(query.toString());
		return q;
	}

	@Override
	public Query select() {
		StringBuilder query = new StringBuilder("");
		query.append("SELECT idparametro, parametro, descripcion, tipodato, valor FROM exhumaciones.paramconfigsistema ");
		Query q = entityManager.createNativeQuery(query.toString());
		StringBuilder orders = createOrder();
		if (!orders.toString().isEmpty())
			query.append("Order By " + orders);
		return q;
	}

	private StringBuilder createOrder() {
		StringBuilder orders = new StringBuilder("");
		List<SortField> sortFields = arrangeableState.getSortFields();

		if(sortFields == null || sortFields.isEmpty())
			return orders;
		
		FacesContext facesContext = FacesContext.getCurrentInstance();
		Iterator<SortField> iSortFields = sortFields.iterator();

		while(iSortFields.hasNext()) {
			SortField sortField = iSortFields.next(); 
			String expression = null;
			String columnName = (String) sortField.getSortBy().getValue(
					facesContext.getELContext());
			if("parametro".equalsIgnoreCase(columnName)) {
				expression = "parametro";
			}else if("descripcion".equalsIgnoreCase(columnName)) {
				expression = "descripcion";
			}else if("tipodato".equalsIgnoreCase(columnName)) {
				expression = "tipodato";
			}else if("valor".equalsIgnoreCase(columnName)) {
				expression = "valor";
			}
			
			if(SortOrder.ascending == sortField.getSortOrder())
				orders.append(expression + " ASC");
			else if(SortOrder.descending == sortField.getSortOrder())
				orders.append(expression + " DESC");
			
			if(iSortFields.hasNext())
				orders.append(",");
		}
		return orders;
	}

}